package bcnet.dao;

import java.util.Date;

import javax.jdo.PersistenceManager;

import bcnet.domain.UserCode;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

public class UserCodeDao {
	public String updateUserCode(String email, String code, String refresh){
		String result="";
		Date updateDate = new Date();
		Key key = KeyFactory.createKey(UserCode.class.getSimpleName(), email);
		PersistenceManager pm = PMF.get().getPersistenceManager();
		
		UserCode userCode;
		
		try{
			userCode = pm.getObjectById(UserCode.class, key);
			if(userCode != null){
				userCode.setCode(code);
				userCode.setRefresh(refresh);
				userCode.setUpdateDate(updateDate);
			}
		}
		catch (javax.jdo.JDOObjectNotFoundException ex){
			userCode = new UserCode(key,code,refresh,updateDate);
		}
		
		try{
			pm.makePersistent(userCode);
			result = "Save successful";
		}
		catch (Exception ex){
			result = "Save fail";
			//result = ex.toString();
		}
		finally{
			pm.close();
		}
		return result;
	}
	
	public String[] getUserCode(String email){
		String result[] = new String[2];
		Key key = KeyFactory.createKey(UserCode.class.getSimpleName(), email);
		PersistenceManager pm = PMF.get().getPersistenceManager();
		
		UserCode userCode;
		
		try{
			userCode = pm.getObjectById(UserCode.class, key);
			if(userCode != null){
				result[0] = userCode.getCode();
				result[1] = userCode.getRefresh();
			}
		}
		catch (javax.jdo.JDOObjectNotFoundException ex){
			result[0] = System.getProperty("default-code");
			result[1] = System.getProperty("default-refreshRate");
		}
		finally{
			pm.close();
		}
		return result;
	}
	

}
